# SimpleOS Makefile
# 使用 make 命令编译和运行操作系统

.PHONY: all build run clean help

# 默认目标
all: build

# 编译操作系统
build: boot.bin kernel.bin
	@echo "=========================================="
	@echo "  Creating OS Image"
	@echo "=========================================="
	@cat boot.bin kernel.bin > os-image.bin
	@dd if=/dev/zero bs=1 count=$$((10240 - $$(stat -c%s os-image.bin))) >> os-image.bin 2>/dev/null || true
	@echo "[OK] OS image created: os-image.bin"
	@ls -lh os-image.bin | awk '{print "  Size: " $$5}'
	@echo ""
	@echo "Build complete! Run with: make run"

# 编译引导扇区
boot.bin: boot.asm
	@echo "[1/2] Compiling boot sector..."
	@nasm -f bin boot.asm -o boot.bin
	@echo "[OK] boot.bin created"

# 编译内核
kernel.bin: kernel.asm
	@echo "[2/2] Compiling kernel..."
	@nasm -f bin kernel.asm -o kernel.bin
	@echo "[OK] kernel.bin created"

# 运行操作系统
run: os-image.bin
	@echo "=========================================="
	@echo "  Starting SimpleOS"
	@echo "=========================================="
	@if command -v qemu-system-i386 > /dev/null 2>&1; then \
		qemu-system-i386 -fda os-image.bin -boot a; \
	elif command -v qemu-system-x86_64 > /dev/null 2>&1; then \
		qemu-system-x86_64 -fda os-image.bin -boot a; \
	else \
		echo "[ERROR] QEMU not found! Please install qemu-system-x86"; \
		exit 1; \
	fi

# 调试模式运行（带GDB）
debug: os-image.bin
	@echo "Starting QEMU with GDB server on port 1234..."
	@qemu-system-i386 -m 128 -drive format=raw,file=os-image.bin -s -S &
	@echo "Connect GDB with: target remote localhost:1234"

# 清理编译文件
clean:
	@echo "Cleaning build files..."
	@rm -f boot.bin kernel.bin os-image.bin
	@echo "Clean complete!"

# 显示帮助信息
help:
	@echo "SimpleOS Makefile"
	@echo ""
	@echo "Available targets:"
	@echo "  make          - Build the OS (default)"
	@echo "  make build    - Build the OS"
	@echo "  make run      - Build and run the OS in QEMU"
	@echo "  make debug    - Run with GDB debugging support"
	@echo "  make clean    - Remove build files"
	@echo "  make help     - Show this help"
	@echo ""
	@echo "Example workflow:"
	@echo "  make && make run"

